package shuishijie.suishijie.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.mob.tools.utils.UIHandler;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import shuishijie.suishijie.BaseActivity;
import shuishijie.suishijie.PayActivity;
import shuishijie.suishijie.R;
import shuishijie.suishijie.WebViewActivity;
import shuishijie.suishijie.util.WechartUtil;

import static android.R.attr.action;


/**
 * Web浏览器画面
 */
public class WebBrowseActivity extends BaseActivity implements View.OnClickListener,  Handler.Callback ,PlatformActionListener {

    /**
     * Logcat TAG
     */
    private static final String TAG = "WebBrowseActivity";

    /**
     * 导航栏
     */
    // TODO: zhangrl
    private View titleLayout;

    /**
     * 自定义WebView
     */
    private CustomWebView browseWebView;
    private String PicName;
    private String orderid;
    private String mobile;
    private String token;
    private String user_id;
    private int THUMB_SIZE = 32;
    private String card_id;
    private String way;
    private String link;
    private String type;
    private String urlnew;
    private Bitmap bp;
    /**
     * 室内地图搜索是否可以直接启动室内地图
     */
    private boolean mapSearch;

    /**
     * 是否从寻车进入，true：是，false：否
     */
    private boolean isParking;

    /**
     * JS API处理回调
     */
//    private AppNativeApi.NativeApiListener jsListener;

    /**
     * 网页url
     */
    private String url;

    /**
     * 导航栏右则按扭文本
     */
    private String rightBtnText;

    /**
     * 正在加载
     */
    private Dialog dl;
    private IWXAPI api;
    public static void showUrl(Context context, String url) {
        showUrl(context, url, null);
    }

    public static void showUrl(Context context, String url, String title) {
        Intent intent = new Intent(context, WebBrowseActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_browse);
        this.browseWebView = (CustomWebView) findViewById(R.id.browseWebView);
        urlnew=getIntent().getStringExtra("url");
        type=getIntent().getStringExtra("type");
        api = WXAPIFactory.createWXAPI(this, WechartUtil.APPID, true);
        api.registerApp(WechartUtil.APPID);
//        this.titleLayout = (TitleLayout) findViewById(R.id.webView_title);

        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        url="https://offline.gvg666.com/dist/index.html#/main/gvgMall";

        URL url1 = null;
        try {
            url1 = new URL(null);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();

            conn.setRequestMethod("GET");

            conn.connect();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                Map<String, List<String>> headFields = conn.getHeaderFields();

                List<String> cookieList = headFields.get("Set-Cookie");

                CookieManager cookieManager = CookieManager.getInstance();

                for(String cookie: cookieList) {

                    cookieManager.setCookie(String.valueOf(url), cookie);

                }

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        // 消息已读清空消息数
//        if (url.startsWith(YoushaaUrlHelper.getMsgURL())) {
//            YoushaaApplication.getApplication().getUserInfo().unreadmsg = null;
//        }
//
        final boolean isShow = intent.getBooleanExtra("isshow", true);
//        rightBtnText = intent.getStringExtra("btntext");
//        if (TextUtils.isEmpty(rightBtnText)) {
//            rightBtnText = "分享";
//        }
//        mapSearch = intent.getBooleanExtra("mapSearch", false);
//        isParking = intent.getBooleanExtra("isParking", false);

        // 是否启用下拉刷新
        boolean enabledSwipeRefresh = intent.getBooleanExtra("enabledSwipeRefresh", true);
        browseWebView.enabledSwipeRefresh(enabledSwipeRefresh);

        browseWebView.getSystemWebView().addJavascriptInterface(new JavaScriptClass(), "android");

//        // 是否注入JS调用java
//        if (intent.getBooleanExtra("injectJs", false)) {
//            browseWebView.setJsCallJava(new JsCallJava(CommenJSFunction2.APP_ObjectName, CommenJSFunction2.class));
//        }

        // 链接点击打开新画面
        browseWebView.setOpenNewWindow(intent.getBooleanExtra("newWindow", false));

        // Progress bar
        browseWebView.setIsShowProgressBar(intent.getBooleanExtra("progress", true));
       // browseWebView.addj


//        titleLayout.getTitleCloseLayout().setVisibility(View.VISIBLE);
//        titleLayout.getTitleCloseLayout().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//
//        titleLayout.getTitleCloseBtn().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//
        // TODO: 2016/5/19
//        titleLayout.setTitleText(title);
//        titleLayout.setOnBackListener(new TitleLayout.OnBackListener() {
//            @Override
//            public void onClick(View v) {
//                if (browseWebView.getSystemWebView().canGoBack()) {
//                    if (browseWebView.isUrlPermissionLayoutVisible()) {
//                        browseWebView.hideUrlPermissionLayout();
//                    } else {
//                        browseWebView.getSystemWebView().goBack();
//                    }
//                } else {
//                    finish();
//                }
//            }
//        });
////
//        titleLayout.setRightBtnVisible(isShow);
////
////        titleLayout.setBtnText(rightBtnText);
////        titleLayout.setButtonClickListener(new TitleLayout.OnButtonClickListener() {
////            @Override
////            public void onClick(View v) {
////                String openClassName = getIntent().getStringExtra("openClassName");
////
////                if (TextUtils.isEmpty(openClassName)) {
////                    //getShareInfo();
////                } else {
////                    Intent intentRight = new Intent();
////                    ComponentName componentNamecom = new ComponentName("com.neusoft.youshaa",
////                            getIntent().getStringExtra("openClassName"));
////                    intentRight.setComponent(componentNamecom);
////                    startActivity(intentRight);
////                }
////            }
////        });
////
////        // 右边Image点击（分享功能）
////        titleLayout.getTitleRightImageLayout().setOnClickListener(new View.OnClickListener() {
////            @Override
////            public void onClick(View v) {
////                getShareInfo();
////            }
////        });
//
//        // 登录状态发生变更处理
//        jsListener = new AppNativeApi.NativeApiListener() {
//            @Override
//            public void onLoginStatusChanged() {
//                String url = browseWebView.getSystemWebView().getUrl();
//
////                if (url != null && url.contains(Constant.LONGIN_URL)) {
////                    runOnUiThread(new Runnable() {
////                        @Override
////                        public void run() {
////                            finish();
////                        }
////                    });
////                } else if (YoushaaApplication.getApplication().getUserInfo() != null) {
//                browseWebView.getSystemWebView().reload();
////                }
//            }
//
//        };
//
//        AppNativeApi.getInstance().addNativeApiListener(jsListener);
//
//
//        // 当WebView加载完成更新Title
//        this.browseWebView.setCustomWebViewListener(new CustomWebView.ICustomWebViewListener() {
//            @Override
//            public void onReceivedTitle(WebView view, String title) {
//                if (TextUtils.isEmpty(titleLayout.getTitleText())) {
//                    titleLayout.setTitleText(title);
//                }
//            }
//
//            @Override
//            public void onOverrideUrlLoading(WebView view, String url) {
//                // 搜索业务的URL的场合
//                switchTitleLayout();
//
////                if (!TextUtils.isEmpty(url) && url.contains(Constant.LONGIN_URL)) {
////                    finish();
////                }
//            }
//        });
//
////        // 搜索功能按扭点击处理
////        titleLayout.getTitleSearchBtn().setOnClickListener(new View.OnClickListener() {
////            @Override
////            public void onClick(View v) {
////                // 隐藏输入法
////                hideIMEWindow();
////                // 执行搜索操作
////                browseWebView.loadUrl(createSearchUrl());
////            }
////        });
//
////        // 搜索文本框中的输入法回车键控制
////        titleLayout.getTitleSearchText().setImeOptions(EditorInfo.IME_ACTION_SEARCH);
////        titleLayout.getTitleSearchText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
////            @Override
////            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
////                boolean blnRet = false;
////                if (actionId == EditorInfo.IME_ACTION_SEARCH ||
////                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
////                    blnRet = true;
////                    // 隐藏输入法
////                    hideIMEWindow();
////                    // 执行搜索操作
////                    browseWebView.loadUrl(createSearchUrl());
////                }
////                return blnRet;
////            }
////        });
//
//        this.browseWebView.setOpenNewWindow(false);
//
        initToolbar();
        // 加载指定URL
        if(type!=null)
        {
            browseWebView.loadUrl(urlnew);
        }else {
            url="https://offline.gvg666.com/dist/index.html#/main/gvgMall";
            browseWebView.loadUrl(url);
        }
        //this.browseWebView.loadUrl(url);

        // 是否进行活动显示检测
        try {
            if (getIntent().getBooleanExtra("showEvent", false)) {
//                showEventPopup();
            }
        } catch (Exception e) {
            // nothing
        }
    }

    private void initToolbar() {
      //  initToolbar("");
//        String title = getIntent().getStringExtra("title");
//
//        if (!getIntent().getBooleanExtra("hideTitle", false) && !TextUtils.isEmpty(title)) {
//            toolbarTitle.setText(title);
//        }
//        browseWebView.setCustomWebViewListener(new CustomWebView.ICustomWebViewListener() {
//            @Override
//            public void onReceivedTitle(WebView view, String title) {
////                if (TextUtils.isEmpty(toolbarTitle.getText())) {
//             //   toolbarTitle.setText(title);
////                }
//            }
//
//            @Override
//            public void onOverrideUrlLoading(WebView view, String url) {
//                Log.e("URL",url);
//                if (url.contains("https://offline.gvg666.com/dist/index.html#/load/registerPay")) {
//                    Intent intent =new Intent(WebBrowseActivity.this,PayActivity.class);
//                    startActivity(intent);
//
//
//                }
//           }
//        });
//        left.setVisibility(View.VISIBLE);
//        left2.setVisibility(View.VISIBLE);
//
//        left2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//        left.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (browseWebView.getSystemWebView().canGoBack()
//                        && !browseWebView.isReceivedError()) {
//                    if (browseWebView.isUrlPermissionLayoutVisible()) {
//                        browseWebView.hideUrlPermissionLayout();
//                    } else {
//                        browseWebView.getSystemWebView().goBack();
//                    }
//                } else {
//                    finish();
//                }
//
//            }
//        });

    }
//    /**
//     * 生成搜索用URL
//     *
//     * @return url
//     */
//    private String createSearchUrl() {
//        StringBuilder searchUrl = new StringBuilder(AppUrlHelper.getRootUrl());
//        String webviewUrl = browseWebView.getSystemWebView().getUrl();
//        if (!TextUtils.isEmpty(webviewUrl)) {
//            if (webviewUrl.contains("boutique/index")) {
//                searchUrl.append("/boutique/index");
//            } else if (webviewUrl.contains("coupon/index")) {
//                searchUrl.append("/coupon/index");
//            } else if (webviewUrl.contains("shop/index")) {
//                searchUrl.append("/shop/index");
//            }
//        }
//
////        String searchKeyWord = titleLayout.getTitleSearchText().getText().toString().trim();
////        if (!TextUtils.isEmpty(searchKeyWord)) {
////            searchUrl.append("?keyword=").append(searchKeyWord);
////        }
//        return searchUrl.toString();
//    }
class JavaScriptClass {
    @JavascriptInterface
    public void  onBtnClick(String l1,String l2,String l3,String
            l4)
    {
        Intent intent =new Intent(WebBrowseActivity.this,PayActivity.class);
        intent.putExtra("orderid",l1);
        intent.putExtra("mobile",l2);
        intent.putExtra("token",l3);
        intent.putExtra("user_id",l4);
        startActivity(intent);
        Log.e("KKK",l1+""+l2+""+l3+""+l4);
        orderid=l1;
        mobile=l2;
        token=l3;
        user_id=l4;
        //  Toast.makeText(WebViewActivity.this, token, Toast.LENGTH_SHORT).show();
    }
    @JavascriptInterface
    public void share(String cardid,String userid,String way)
    {
        link="https://offline.gvg666.com/dist/index.html#/load/download?cardId="+cardid+"&userId="+userid;

        if(way.equals("0"))
        {
            weChat();
        }else
        {
            friendCircle();
        }
    }

}
    @Override
    protected void onResume() {
        super.onResume();
        if (browseWebView.isReceivedError()) {
            browseWebView.getSystemWebView().reload();
        }
    }

//    @Override
//    public void initView() {
//        // nothing
//    }
//
//    @Override
//    public void initEvent() {
//        // nothing
//    }
//
//    @Override
//    public View getTitleLayout() {
//        return titleLayout;
//    }
public void weChat() {
    //微信
    if (!api.isWXAppInstalled()) {
        Toast.makeText(this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
        //AlertUtil.t(InviteFriendActivity.this, "您还未安装微信客户端", Toast.LENGTH_SHORT);
        return;
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
//                Bitmap bmp = null;
//                try {
//                    bmp = Glide.with(getApplicationContext())
//                            .load("https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E6%B7%98%E5%AE%9D&step_word=&hs=0&pn=1&spn=0&di=61040852510&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=2111509796%2C1998071314&os=3568410211%2C1864346178&simid=4213041868%2C919940859&adpicid=0&lpn=0&ln=1978&fr=&fmq=1514044300007_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fimg.weixinyidu.com%2F151228%2F5767343c.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bojtxtgyt17_z%26e3Bv54AzdH3Fg_d0c8a0l&gsm=0&rpstart=0&rpnum=0")
//                            .asBitmap()
//                            .centerCrop()
//                            .into(THUMB_SIZE, THUMB_SIZE)
//                            .get();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    Log.e("jin", "InterruptedException: ");
//
//                } catch (ExecutionException e) {
//                    e.printStackTrace();
//                    Log.e("jin", "ExecutionException: ");
//                } finally {
            Message msg = new Message();
            msg.arg1 = 4;
            msg.arg2 = action;
            // msg.obj = bmp;
            UIHandler.sendMessage(msg, WebBrowseActivity.this);
        }
        //}
    }).start();
}
public void friendCircle() {
    //朋友圈
    if (!api.isWXAppInstalled()) {
        Toast.makeText(WebBrowseActivity.this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
        return;
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
//                    Bitmap bmp = null;
//                    try {
//                        bmp = Glide.with(WebViewActivity.this)
//                                .load("mobile/images/btcf.png")
//                                .asBitmap()
//                                .centerCrop()
//                                .into(THUMB_SIZE, THUMB_SIZE)
//                                .get();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                        Log.e("jin", "InterruptedException: ");
//
//                    } catch (ExecutionException e) {
//                        e.printStackTrace();
//                        Log.e("jin", "ExecutionException: ");
//                    } finally {
            Message msg = new Message();
            msg.arg1 = 5;
            msg.arg2 = action;
            //msg.obj = bmp;
            UIHandler.sendMessage(msg, WebBrowseActivity.this);
        }
        // }
    }).start();
}
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean blnRet = true;

        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0 && browseWebView.getSystemWebView().canGoBack()
                && !browseWebView.isReceivedError()) {
            if (browseWebView.isUrlPermissionLayoutVisible()) {
                browseWebView.hideUrlPermissionLayout();
            } else {
                browseWebView.getSystemWebView().goBack();
            }
        } else {
            blnRet = super.onKeyDown(keyCode, event);
        }
        return blnRet;
    }

    /**
     * 当前Url是否为可分享URL
     *
     * @param url url
     * @return true：是可分享URL，false：不可分享URL
     */
    private boolean isShareUrl(String url) {
        boolean blnRet = false;
//        if (!TextUtils.isEmpty(url) && (url.contains(Constant.SHARE_FILTER_URL) ||
//                url.contains(Constant.WAPAGE_URL) ||
//                url.contains(Constant.WAPAGE_DEV_URL))) {
//            blnRet = true;
//        }
        return blnRet;
    }

    /**
     * 当前Url是否为搜索业务的URL
     *
     * @param url url
     * @return true:是搜索业务的URL, false:不是搜索业务的URL
     */
    private boolean isSearchUrl(String url) {
        boolean blnRet = false;
        if (!TextUtils.isEmpty(url) && (url.contains("boutique/index")
                || url.contains("coupon/index") || url.contains("shop/index"))) {
            blnRet = true;
        }
        return blnRet;
    }


    /**
     * 切换title部UI显示内容
     */
    private void switchTitleLayout() {
        String url = browseWebView.getSystemWebView().getUrl();
        if (isSearchUrl(url)) {
//            if (!"NeuECP".equals(browseWebView.getSystemWebView().getTitle())) {
//                titleLayout.getTitleSearchText().setText(browseWebView.getSystemWebView().getTitle());
//            }
//            titleLayout.getTitleSearchLayout().setVisibility(View.VISIBLE);
//            titleLayout.getTitleRightImageLayout().setVisibility(View.GONE);
//            titleLayout.findViewById(R.id.title_center_name).setVisibility(View.GONE);
        } else {
//            if (titleLayout.getTitleSearchLayout().getVisibility() == View.VISIBLE) {
//                titleLayout.getTitleSearchLayout().setVisibility(View.GONE);
//                hideIMEWindow();
//            }
//            titleLayout.findViewById(R.id.title_center_name).setVisibility(View.VISIBLE);
//            if (isShareUrl(url)) {
//                titleLayout.getTitleRightImageLayout().setVisibility(View.VISIBLE);
//            } else {
//                titleLayout.getTitleRightImageLayout().setVisibility(View.GONE);
//            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

//    @Override
//    public boolean handleMessage(Message msg) {
//        return false;
//    }

    @Override
    public void onClick(View v) {

    }
    public boolean handleMessage(Message message) {
        String text = "";
        switch (message.arg1) {
            case 1: {
                // 成功
                okhttp3.internal.platform.Platform plat = (okhttp3.internal.platform.Platform) message.obj;
                // text = plat.getName() + "share completed ";
                text = "分享成功 ";
            }
            Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
            break;
            case 2: {
                // 失败
                if ("WechatClientNotExistException".equals(message.obj.getClass().getSimpleName())) {
                    //text = this.getString(R.string.wechat_client_inavailable);
                } else if ("WechatTimelineNotSupportedException".equals(message.obj.getClass().getSimpleName())) {
                    // text = this.getString(R.string.wechat_client_inavailable);
                } else {
                    //text = this.getString(R.string.share_failed);
                }
            }
            Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
            break;
            case 3: {
                // 取消
                okhttp3.internal.platform.Platform plat = (okhttp3.internal.platform.Platform) message.obj;
                // text = plat.getName() + " canceled ";
                text = "取消分享 ";
            }
            Toast.makeText(this, "取消分享", Toast.LENGTH_SHORT).show();
            break;
            case 4:
                Bitmap bmp = (Bitmap) message.obj;
                WXWebpageObject webpageObject = new WXWebpageObject();
                webpageObject.webpageUrl =link;
                WXMediaMessage msg = new WXMediaMessage(webpageObject);
                msg.title = "世界村水世界";
                msg.description = "邀请您加入水世界平台，乐享安全、高收益的投资回报！";
                msg.setThumbImage(bp);
                if (bmp != null) {
                    bmp.recycle();
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.message = msg;
                req.transaction = "webpage";
                req.scene = SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);

                break;
            case 5:
                //Bitmap bmp1 = (Bitmap) message.obj;
                Resources res = getResources();
                bp = BitmapFactory.decodeResource(res, R.mipmap.logo);
                WXWebpageObject webpageObject1 = new WXWebpageObject();
                webpageObject1.webpageUrl =link;
                WXMediaMessage msg1 = new WXMediaMessage(webpageObject1);
                msg1.title = "世界村水世界";
                msg1.description = "邀请您加入水世界平台，乐享安全、高收益的投资回报！";
                msg1.setThumbImage(bp);
                if (bp != null) {
                    bp.recycle();
                }
                SendMessageToWX.Req req1 = new SendMessageToWX.Req();
                req1.message = msg1;
                req1.transaction = "webpage";
                req1.scene = SendMessageToWX.Req.WXSceneTimeline;
                api.sendReq(req1);

                break;
            default:
                break;

        }

        //        AlertUtil.t(this, text);
        return false;
    }
    @Override
    public void onComplete(cn.sharesdk.framework.Platform platform, int i, HashMap<String, Object> hashMap) {
        Message msg = new Message();
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onError(cn.sharesdk.framework.Platform platform, int i, Throwable throwable) {
        Message msg = new Message();
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = throwable;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onCancel(cn.sharesdk.framework.Platform platform, int i) {
        Message msg = new Message();
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }
}
